$(function(){
	var ap = new AjaxOperator();
    var manager = new CustomerManager();
    var thbody = $("#content");
    var customers;
    //初始化页面数据
    manager.findAll("findAll",findCallBack);
    function findCallBack(data){
    	customers = data;
    	manager.render(thbody, customers);
    	manager.addDeleteEvent("deleteCustomer",deleteCallBack);
    	manager.addUpdateEvent("toUpdate",toUpdateCallBack);
    }
    function toUpdateCallBack(data){
    	$("#updateModal input[name='id']").val(data.id);
    	$("#updateModal input[name='name']").val(data.name);
    	$("#updateModal input[name='salary']").val(data.salary);
        if(data.sex){
            $("#updateModal input[name='sex']").last().removeAttr("checked");
            $("#updateModal input[name='sex']").first().attr("checked","checked");
        }else {
            $("#updateModal input[name='sex']").first().removeAttr("checked");
            $("#updateModal input[name='sex']").last().attr("checked","checked");
        }
    	var birth = manager.formatDate(new Date(data.birth));
    	$("#updateModal input[name='birth']").val(birth);
    }
    function deleteCallBack(data){
//    	alert(JSON.stringify(data));
//    	var index = customers.indexOf(data);
//    	customers.splice(index,1);
//    	manager.render(thbody, customers);
    	if(data){
    		alert("delete success");
    		manager.findAll("findAll",findCallBack);
    	}
    }
    
    //增加用户
    $("#add").on("click",function(e){
        var name = $("input[name='name']").val();
        var sex = $("input[name='sex']:checked").val();
        var salary=$("input[name='salary']").val();
        var birth = $("input[name='birth']").val();
        var customer = {name:name,sex:sex,salary:salary,birth:birth};
        manager.addCustomer("addCustomer",customer,addCallBack);
    });
    function addCallBack(data){
    	if(data){
    		alert("add success");
    		customers.push(data);
    		manager.render(thbody, customers);
    		manager.addDeleteEvent("deleteCustomer",deleteCallBack);
    		manager.addUpdateEvent("toUpdate",updateCallBack);
    	}else {
    		alert("add fail!");
    	}
    }
    
    //更新用户
    $("#update").on("click",function(e){
    	var id = $("#updateModal input[name='id']").val();
    	var name = $("#updateModal input[name='name']").val();
    	var salary = $("#updateModal input[name='salary']").val();
        var sex = $("#updateModal input[name='sex']:checked").val();
    	var birth = $("#updateModal input[name='birth']").val();
    	var customer = {id:id,name:name,sex:sex,salary:salary,birth:birth};
//    	alert(JSON.stringify(customer));
    	manager.updateCustomer("updateCustomer",customer,updateCallBack);
    });
    function updateCallBack(data){
    	if(data){
//    		alert("dd->"+JSON.stringify(data));
    		manager.findAll("findAll",findCallBack);
    		alert("update success");
    		$("#updateModal").modal('hide');
    	}else {
    		alert("add fail!");
    	}
    }
});